package com.doubao.msghadler;

import com.alibaba.fastjson.JSON;
import com.doubao.protocol.Msg;
import com.doubao.protocol.TextMsg;
import com.doubao.service.ISOfferlineMsgService;
import com.doubao.strategy.tplStrategy.TplStrategyContext;
import com.doubao.util.ChannelManage;
import com.doubao.util.SpringContextUtil;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * description:MsgHandler
 * <p>
 * author:sult
 * time: 2018/11/2 11:30
 **/
public class MsgHandler extends AbstractMsgHandler {

    public ISOfferlineMsgService iSOfferlineMsgService = SpringContextUtil.getBean("SOfferlineMsgServiceImpl", ISOfferlineMsgService.class);

    private static final Logger log = LoggerFactory.getLogger(MsgHandler.class);


    public MsgHandler(Msg msg, Channel fromChannel) {
        super(msg, fromChannel);
    }

    @Override
    protected Boolean sendWechatTplMsg() {
        saveOfferLinerMsg();
        saveMsgLog();
        return TplStrategyContext.sendTplMsg((TextMsg)msg);
    }

    @Override
    protected Boolean sendWebSoketMsg() {
        Boolean success=ChannelManage.sendMsg(msg);
        if(!success){
            saveOfferLinerMsg();
        }

        saveMsgLog();
        return success;
    }

    private void saveMsgLog() {
        // ToDO 记录消息日志稍后实现
        log.info(" 记录聊天记录！");
    }

    /**
     * 保存离线消息
     */
    private void saveOfferLinerMsg() {
        try {
            log.info("保存离线消息！内容【{}】", JSON.toJSONString(msg));
            iSOfferlineMsgService.saveOfferLineMsg(msg);
        } catch (Exception e) {
            log.error("记录未读消息失败！！错误信息：{}",e);
            e.printStackTrace();
        }
    }

}
